//
//  XCCycleLayout.swift
//  XCCycleBanner
//
//  Created by edy on 2023/7/10.
//

import UIKit


public class XCCycleLayoutParams {
    
    // base
    public var itemSize: CGSize?
    public var itemSpacing: CGFloat = 0.0
    public var scrollDirection: UICollectionView.ScrollDirection = .horizontal
}

// MARK: - Set function
public extension XCCycleLayoutParams {
    
    func itemSize(_ itemSize: CGSize) -> XCCycleLayoutParams {
        self.itemSize = itemSize
        return self
    }
    
    func itemSpacing(_ itemSpacing: CGFloat) -> XCCycleLayoutParams {
        self.itemSpacing = itemSpacing
        return self
    }
    
    func scrollDirection(_ scrollDirection: UICollectionView.ScrollDirection) -> XCCycleLayoutParams {
        self.scrollDirection = scrollDirection
        return self
    }

}


class XCCycleLayout: UICollectionViewFlowLayout {

    override init() {
        super.init()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    var params: XCCycleLayoutParams? {
        didSet {
            if let params = params {
                shouldInvalidateLayout = true
                scrollDirection = params.scrollDirection
                itemSize = params.itemSize ?? collectionView?.bounds.size
                    ?? CGSize(width: 2, height: 2)
                minimumLineSpacing = params.itemSpacing
                minimumInteritemSpacing = params.itemSpacing
            } else {
                scrollDirection = .horizontal
            }
        }
    }
    
    /// Fixed cell offset bug:  when XIB loaded JXBanner with Pagecount equal to 1
    var shouldInvalidateLayout = true
    
    var isPagingEnabled: Bool = true
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) ->
        Bool {
            if shouldInvalidateLayout {
                shouldInvalidateLayout = false
                return true
            }
            return super.shouldInvalidateLayout(forBoundsChange: newBounds)
    }
    
    override func prepare() {
        super.prepare()
        
        // Set the margins
        if isPagingEnabled {
            let inset: CGFloat = (collectionView!.frame.width - itemSize.width) * 0.5
            sectionInset = UIEdgeInsets(top: 0,
                                        left: inset,
                                        bottom: 0,
                                        right: inset)
        }

    }
    
}


